<template>
  <el-form :model="formData" ref="formRef" :rules="rules" label-position="left" label-width="77px" size="medium"
    @submit.native.prevent>

    <el-form-item label="学科：" prop="subjectID" class="required">
      <el-select
        v-model="formData.subjectID"
        class="full-width-input"
        clearable
        @change="subjectIdChange(formData.subjectID)"
        :style="'width: 450px'"
      >
        <el-option
          v-for="(item, index) in subjectIDOptions"
          :key="index"
          :label="item.label"
          :value="item.value"
          :disabled="item.disabled"
        ></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="目录：" prop="catalogID" class="required">
      <el-select
        v-model="formData.catalogID"
        class="full-width-input"
        clearable
        :style="'width: 450px'"
      >
        <el-option
          v-for="(item, index) in catalogIDOptions"
          :key="index"
          :label="item.label"
          :value="item.value"
          :disabled="item.disabled"
        ></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="企业：" prop="enterpriseID" class="required">
      <el-select
        v-model="formData.enterpriseID"
        class="full-width-input"
        clearable
        :style="'width: 450px'"
      >
        <el-option
          v-for="(item, index) in enterpriseIDOptions"
          :key="index"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="城市：" prop="province" class="required">
      <el-select
        class="filter-item"
        style="width: 220px"
        v-model="formData.province"
        @keyup.enter="handleFilter"
        @change="handleProvince"
        filterable
      >
        <el-option
          v-for="item in citySelect.province"
          :key="item"
          :label="item"
          :value="item"
        ></el-option>
      </el-select>
      <el-select
        class="filter-item"
        style="width: 220px;"
        v-model="formData.city"
        @keyup.enter="handleFilter"
        filterable
      >
        <el-option
          v-for="item in citySelect.cityDate"
          :key="item"
          :label="item"
          :value="item">
        </el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="方向：" prop="direction" class="required">
      <el-select
        v-model="formData.direction"
        class="full-width-input"
        clearable
        :style="'width: 450px'"
      >
        <el-option
          v-for="(item, index) in directionOptions"
          :key="index"
          :label="item"
          :value="item"
        ></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="题型：" prop="questionType" class="required">
      <el-radio-group v-model="formData.questionType">
        <el-radio
          v-for="(item, index) in questionTypeOptions"
          :key="index" :label="item.value"
          :disabled="item.disabled"
          style="{display: inline}"
        >{{item.label}}</el-radio>
      </el-radio-group>
    </el-form-item>

    <el-form-item label="难度：" prop="difficulty" class="required">
      <el-radio-group v-model="formData.difficulty">
        <el-radio
          v-for="(item, index) in difficultyOptions"
          :key="index"
          :label="item.value"
          :disabled="item.disabled"
          style="{display: inline}"
        >{{item.label}}</el-radio>
      </el-radio-group>
    </el-form-item>

    <el-row>
      <el-form-item label="题干：" prop="question" style="height: 180px">
        <quill-editor
          v-model="formData.question"
          :options="editorOption"
          style="height: 120px"
        >
        </quill-editor>
      </el-form-item>
    </el-row>

    <el-row :gutter="15" v-if="formData.questionType !== 3">
     <el-form-item label="选项：" >
      <!-- 单选 -->
      <el-radio-group v-if="formData.questionType === 1" @change="radioGroup" v-model="radio">
       <el-row type="flex" align="middle" v-for="(item, index) in formData.options" :key="item.code" style="padding: 10px 0">
         <el-radio :label="index + 1">{{item.code}}</el-radio>
         <el-input v-model="item.title" />
         <!-- 图片 -->
       </el-row>
      </el-radio-group>

      <!-- 多选 -->
      <el-checkbox-group v-if="formData.questionType === 2" @change="checkedFn" v-model="checkbox">
       <el-row type="flex" align="middle" v-for="item in formData.options" :key="item.code" style="padding: 10px 0">
         <el-checkbox :label="item.code">{{item.code}}</el-checkbox>
         <el-input :style="{width: '30%', marginLeft: '25px'}" v-model="item.title" />
         <!-- 图片 -->
       </el-row>
      </el-checkbox-group>

      <el-row type="flex" align="middle">
        <!-- 当选中为多选时启用 -->
       <el-button type="danger" :disabled="formData.questionType !==2" size="mini" @click="addRadio">+增加选项与答案</el-button>
      </el-row>
     </el-form-item>
    </el-row>
    
    <el-form-item label="解析视频：" label-width="95px">
      <el-input
        v-model="formData.videoURL"
        type="text"
        clearable
        :style="'width: 450px'"
      ></el-input>
    </el-form-item>

    <el-row>
      <el-form-item label="答案解析：" prop="answer" style="height: 180px" label-width="95px">
        <quill-editor
          v-model="formData.answer"
          :options="editorOption"
          style="height: 120px"
        >
        </quill-editor>
      </el-form-item>
    </el-row>

    <el-form-item label="题目备注：" prop="question" label-width="95px">
      <el-input
       type="textarea"
       v-model="formData.remarks"
       rows="4"
       :style="{width: '450px'}"
      ></el-input>
    </el-form-item>

    <el-form-item label="试题标签：" prop="tags" label-width="95px">
      <el-select
       v-model="formData.tags"
       multiple
       filterable
       allow-create
       default-first-option
       class="full-width-input" :style="'width: 450px'"
      >
        <el-option
         v-for="item in tagsOptions"
         :key="item.value"
         :label="item.label"
         :value="item.label"
        ></el-option>
      </el-select>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" class="submitBtn" @click="submitForm">确认提交</el-button>
    </el-form-item>

  </el-form>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import { simple as subjectIdSimple } from '@/api/hmmm/subjects.js'
import { simple as dirSimple } from '@/api/hmmm/directorys.js'
import { simple as tagsSimple } from '@/api/hmmm/tags.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { direction as directionList, difficulty, questionType } from '@/api/hmmm/constants.js'
import { list as enterpriseIDList } from '@/api/hmmm/companys.js'
import { add,detail,update } from '@/api/hmmm/questions.js'

  export default {
    name: 'questionsNewForm',
    components: {
      quillEditor
    },
    props: {
    },
    data() {
      return {
        radio: 1, // 选项
        checkbox: [], // 多选
        
        formData: { // 表单对象数据
          subjectID: "", // 学科id
          catalogID: "", // 目录id
          enterpriseID: "", // 企业id
          province: "", // 城市名
          city: "", // 区县名
          direction: "", // 方向名
          questionType: 1, // 题型
          difficulty: 1, // 难度
          videoURL: "", // 视频地址
          remarks: "",  // 题目备注
          tags: "", // 试题标签
          question: '', // 题干内容
          answer: '', // 答案解析内容
          // 选项数据
          options: [
            {
              code: 'A', // ABCD
              title: '', // 标题
              img: '', // 图片路径
              isRight: '1' // 是否为正确
            },
            {
              code: 'B', // ABCD
              title: '', // 标题
              img: '', // 图片路径
              isRight: '0' // 是否为正确
            },
            {
              code: 'C', // ABCD
              title: '', // 标题
              img: '', // 图片路径
              isRight: '0' // 是否为正确
            },
            {
              code: 'D', // ABCD
              title: '', // 标题
              img: '', // 图片路径
              isRight: '0' // 是否为正确
            }
          ],
        },
        rules: {
          subjectID: [
            { required: true, message: '请选择学科', trigger: 'change' }
          ],
          catalogID: [
            { required: true, message: '请选择目录', trigger: 'change' }
          ],
          enterpriseID: [
            { required: true, message: '请选择企业', trigger: 'change' }
          ],
          province: [
          { required: true, message: '请选择省份', trigger: 'change' }
          ],
          direction: [
            { required: true, message: '字段值不可为空', trigger: 'change' }
          ],
          questionType: [
            { required: true, message: '字段值不可为空', trigger: 'change' }
          ],
          difficulty: [
            { required: true, message: '字段值不可为空', trigger: 'change' }
          ],
          answer: [
            { required: true, message: '字段值不可为空', trigger: 'change' }
          ],
          question: [
            { required: true, message: '字段值不可为空', trigger: 'change' }
          ],
          remarks: [
            { required: true, message: '字段值不可为空', trigger: 'change' }
          ],
          tags: [
            { required: true, message: '字段值不可为空', trigger: 'blur' }
          ]
        },
        subjectIDOptions: [], // 学科数据列表
        catalogIDOptions: [], // 目录数据列表
        enterpriseIDOptions: [], // 企业数据列表
        citySelect: {
          province: [], // 市区数据列表
          cityDate: [] //  区县数据列表
        },
        directionOptions: directionList, // 方向数据列表
        questionTypeOptions: questionType, // 题型
        difficultyOptions: difficulty, // 难度
        tagsOptions: [], // 试题标签数据
        editorOption: { // 富文本配置
          modules: {
            toolbar: [
              ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
              [{ list: 'ordered' }, { list: 'bullet' }], // 有序列表，无序列表
              ['blockquote'], // 引用
              ['code-block', 'image', 'link'] // 代码快, 图片, 链接
            ]
          }
        }
      }
    },
    computed: {
      editor() {
        return this.$refs.myQuillEditor.quill
      }
    },
    watch: {},
    created() {
      // 简单数据列表
      this.getList()
      // 城市数据列表
      this.getCityData()
      // 回显数据
      if(this.$route.query.id) {
        this.displayList()
      }
    },
    mounted() {},
    methods: {
      // 修改，数据回显
      async displayList() {
        try {
          // 获取到题目id，根据题目id请求数据 this.$route.query.id
          const { data } = await detail({ id: this.$route.query.id })
          // 当前选中的复选框
          data.options.forEach(item=> {
            if(item.isRight === 1) {
              this.checkbox.push(item.code)
            }
          })
          // 处理 题型 难度
          data.difficulty = +data.difficulty
          data.questionType = +data.questionType
          // 处理标签
          data.tags = [data.tags]
          // 将数据覆盖formData对象
          this.formData = data
          this.subjectIdChange(data.subjectID)
        } catch (error) {
          console.log(error)
        }
      },
      // 添加多选框
      addRadio () {
        const arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

        // 追加数据
        this.formData.options.push({
          code: arr[this.formData.options.length],
          title: '', // 标题
          img: '', // 图片路径
          isRight: '0' // 是否为正确
        })
      },
      // 单选是否为正确答案
      radioGroup (index) {
        this.formData.options.forEach((item, i) => {
          item.isRight = index === i + 1 ? '1' : '0'
        })
      },
      // 多选正确答案
      checkedFn () {
        this.formData.options.forEach((item,i)=> {
          // 如果能在复选数组中找到，就表示为正确答案
          item.isRight = this.checkbox.find(t=>item.code===t) ? '1' : 0
        })
      },
      // 获取省
      getCityData: function () {
        this.citySelect.province = provinces()
      },
      // 选省获取到市
      handleProvince: function (e) {
        this.citySelect.cityDate = citys(e)
        this.formData.city = this.citySelect.cityDate[0]
      },
      // 获取目录、标签
      async subjectIdChange(value) {
        try {
          const {data: dirRes} = await dirSimple({
            subjectID: value
          })
          const {data: tagsRes} = await tagsSimple({
            subjectID: value
          })
          // console.log(res)
          this.catalogIDOptions = dirRes
          this.tagsOptions = tagsRes
        } catch (error) {
          console.log(error)
        }
      },
      // 获取学科、企业
      async getList() {
        try {
          // 学科
          const {data: simpleRes} = await subjectIdSimple()
          // console.log(res)
          this.subjectIDOptions = simpleRes
          // 企业
          const {data: {items}} = await enterpriseIDList({ pagesize:100 })
           // 筛选数据
          this.enterpriseIDOptions = items.map(item=> ({
            label: item.company,
            value: item.id
          }))
        } catch (error) {
          console.log(error)
        }
      },

      // 表单提交
      async submitForm() {
        try {
          // 表单预验证
          await this.$refs['formRef'].validate()
          // 处理数据
          for (const key in this.formData) {
            if (typeof this.formData[key] !== 'object' && this.formData[key] !== this.formData.subjectID && this.formData[key] !== this.formData.catalogID && this.formData[key] !== this.formData.enterpriseID && this.formData[key] !== this.formData.id) {
              this.formData[key] = this.formData[key] + ''
            }
          }
          // tags => string
          this.formData.tags = this.formData.tags.join(',')
          //TODO: 提交表单
          // 发起请求
          if (this.$route.query.id) {
            // 修改题目
            await update(this.formData)
            this.$message.success('修改成功')
          } else {
            // 添加题目
            await add(this.formData)
            this.$message.success('添加成功')
          }
          // 跳转到基础题库
          this.$router.push('/questions/list')
        } catch (error) {
          console.log(error)
        }
        
      },
      // resetForm() {
      //   this.$refs['formRef'].resetFields()
      // }
    },
    
  }
  
</script>

<style lang="scss">
  .el-input-number.full-width-input,
  .el-cascader.full-width-input {
    width: 100% !important;
  }
  
  .el-form-item--medium {
    .el-radio {
      line-height: 36px !important;
    }
    
    .el-rate {
      margin-top: 8px;
    }
  }
  
  .el-form-item--small {
    .el-radio {
      line-height: 32px !important;
    }
    
    .el-rate {
      margin-top: 6px;
    }
  }
  
  .el-form-item--mini {
    .el-radio {
      line-height: 28px !important;
    }
    
    .el-rate {
      margin-top: 4px;
    }
  }
  
  .clear-fix:before,
  .clear-fix:after {
    display: table;
    content: "";
  }
  
  .clear-fix:after {
    clear: both;
  }
  
  .float-right {
    float: right;
  }
  
</style>

<style lang="scss" scoped>
  div.table-container {
    table.table-layout {
      width: 100%;
      table-layout: fixed;
      border-collapse: collapse;

      td.table-cell {
        display: table-cell;
        height: 36px;
        border: 1px solid #e1e2e3;
      }
    }
  }
  
  
  .label-left-align ::v-deep .el-form-item__label {
    text-align: left;
  }
  
  .label-center-align ::v-deep .el-form-item__label {
    text-align: center;
  }
  
  .label-right-align ::v-deep .el-form-item__label {
    text-align: right;
  }
  
  
  .static-content-item {
    min-height: 20px;
    display: flex;
    align-items: center;

    ::v-deep .el-divider--horizontal {
      margin: 0;
    }
  }

  .city {
    margin-left: -10px;
  }

  .province {
    margin-left: 10px;
  }

  .submitBtn {
    margin-left: 25px;
  }

  
</style>